/**
 * 同步ajax
 */
var ajaxResult = function(url,params,callBack){
	$.ajax({
		type:'POST',
		url:url,
		async:false,
		data:params,
		dataType:'json',
		success:function(result){
			if(result && result.success){
				 callBack(true,result);
			}else{
				 callBack(false,result);
			}
		}
	});
}

/**
 * 异步ajax
 */
var ajaxAsyncResult = function(url,params,callBack){
	$.ajax({
		type:'POST',
		url:url,
		async:true,
		data:params,
		dataType:'json',
		success:function(result){
			if(result && result.success){
				callBack(true,result);
			}else{
				callBack(false,result);
			}
		}
	});
}

/**
 * 异步get ajax
 */
var ajaxAsyncGetResult = function(url,params,callBack){
	$.ajax({
		type:'GET',
		url:url,
		async:true,
		data:params,
		dataType:'json',
		success:function(result){
			if(result && result.success){
				callBack(true,result);
			}else{
				callBack(false,result);
			}
		}
	});
}
/**
 * yyyy-MM-dd hh:mm:ss
 * @param value
 * @returns {String}
 */
function formatDate(value){
				var date = new Date(value);
		       	var year  = date.getFullYear();
		       	var month = date.getMonth()+1;
		       	var day = date.getDate();
		       	var hour = date.getHours();
		       	var minutes = date.getMinutes();
		       	var second = date.getSeconds();
		       	return year+"-"+cover(month)+"-"+cover(day)+" "+cover(hour)+":"+cover(minutes)+":"+cover(second);
}
	
/**
 * 补足2位
 */
function cover(value){
		if(value.toString().length <=1){
			value = "0"+value;
		}
		return value;
}

//格式化显示日期时间
//参数x : 待显示的日期时间，示例： new Date()
//参数y: 需要显示的格式，示例：yyyy-MM-dd hh:mm:ss
function date2str(x, y) {
	var z = {
	   y: x.getFullYear(),
	   M: x.getMonth() + 1,
	   d: x.getDate(),
	   h: x.getHours(),
	   m: x.getMinutes(),
	   s: x.getSeconds()
	};
	return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {
	   return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
	});
}

function formatDateStyle(value){
	var date = new Date(value);
	date.setHours(date.getHours());
	var now= new Date();
	 //计算时间间隔，单位为秒 
    var inter = parseInt((now.getTime() - date.getTime())/1000);
    if(inter <= 0){
    	return "刚刚";
    }else if(inter > 0 && inter <=59){
        return inter+"秒前";
    }else if(inter >= 60 && inter < 60*60){//多少分钟前
        return parseInt(inter/60) + "分钟前";
    }else if(inter >60*60 && inter < 60*60*24){ //多少小时前(小于1天)
        return parseInt(inter/60/60) + "小时前";
    }else if(inter >=60*60*24 && inter < 60*60*24*15){ //多少小时前(1~15天)
        return parseInt(inter/60/60/24) + "天前";
    }else if(now.getFullYear() == date.getFullYear() && inter >0){//本年度内，日期不同，取日期+时间  格式如  06-13 22:11
    	return cover(date.getMonth()+1)+"-"+cover(date.getDate().toString())+" "+cover(date.getHours().toString())+":"+cover(date.getMinutes().toString());
    }else{
    	return date2str(date,"yyyy-MM-dd");
    }
}

/**
02
 * 获取指定时间的友好时间字符串。
03
 * @param str 指定的时间字符串，如yyyy-MM-dd HH:mm:ss
04
 * @param now 当前时间，允许时间戳，GMT时间，如果该参数为undefined，则使用浏览器时间。
05
 */
function getFriendlyTime(str, now){
    var currentTime = new Date(now);
    var arr = str.split(/\s+/gi);
    var arr1, arr2, oldTime, delta;
    var getIntValue = function(ss, defaultValue){
        try{
            return parseInt(ss, 10);
        }catch (e){
            return defaultValue;
        }
    };
    var getWidthString = function(num){
        return num < 10 ? ("0" + num) : num;
    };
    if(arr.length >= 2){
        arr1 = arr[0].split(/[\/\-]/gi);
        arr2 = arr[1].split(":");
        oldTime = new Date();
        oldTime.setYear(getIntValue(arr1[0], currentTime.getFullYear()));
        oldTime.setMonth(getIntValue(arr1[1], currentTime.getMonth() + 1) - 1);
        oldTime.setDate(getIntValue(arr1[2], currentTime.getDate()));
 
        oldTime.setHours(getIntValue(arr2[0], currentTime.getHours()));
        oldTime.setMinutes(getIntValue(arr2[1], currentTime.getMinutes()));
        oldTime.setSeconds(getIntValue(arr2[2], currentTime.getSeconds()));
 
        delta = currentTime.getTime() - oldTime.getTime();
        if(delta <= 6000){
            return "1分钟内";
        }
        else if(delta < 60 * 60 * 1000){
            return Math.floor(delta / (60 * 1000)) + "分钟前";
        }
        else if(delta < 24 * 60 * 60 * 1000){
            return Math.floor(delta / (60 * 60 * 1000)) + "小时前";
        }
        else if(delta < 3 * 24 * 60 * 60 * 1000){
            return Math.floor(delta / (24 * 60 * 60 * 1000)) + "天前";
        }
        else if(currentTime.getFullYear() != oldTime.getFullYear()){
            return [getWidthString(oldTime.getFullYear()), getWidthString(oldTime.getMonth() + 1), getWidthString(oldTime.getDate())].join("-")
        }
        else{
            return [getWidthString(oldTime.getMonth() + 1), getWidthString(oldTime.getDate())].join("-");
        }
    }
    return "";
}

//表单赋值
/*var setForm = function(formId,data){
	var formFields = $(formId).serializeArray();
    $.each(formFields, function() {
    	if(this.name == ){
    		
    	}
      $('#'+[this.name] = this.value;
    });
};*/

//消息弹出框
var alertMessageWin = function(message){
	var _html = "<div id=\"alert-win\" class=\"alert-win\" style=\"display: block;\">";
		_html += "<div class=\"alert-title\">";
		_html += "<span style=\"margin-top: -6px; float: left;margin-left: 3px;\">消息提示</span>";
		_html += "<a class=\"alert-close\" href=\"javascript:void(0);\">";
		_html +="<span style=\"float: right;\"><img src=\"images/close.png\"></span>";
		_html +="</a></div>";
		_html +="<div class=\"alert-msg\">"+message+"</div></div>";
		_html +="<div id=\"alert-bg\" class=\"alert-bg\" style=\"display: block;\"></div>";
		$('body').append(_html);
}

//消息确认框
var confirmMessageWin = function(message){
	var _html = "<div  class=\"confirm-win\" style=\"display: block;\">";
	_html += "<div class=\"confirm-title\">";
	_html += "<span style=\"margin-top: -6px; float: left;margin-left: 3px;\">消息提示</span>";
	_html += "<a class=\"confirm-close\" href=\"javascript:void(0);\">";
	_html +="<span style=\"float: right;\"><img src=\"images/close.png\"></span>";
	_html +="</a></div>";
	_html +="<div class=\"confirm-msg\">"+message+"</div>";
	_html += "<div class=\"confirm-btn\"><div><a id=\"confirm-btn-ok\" href=\"javascript:void(0);\" >确定</a></div>";  
    _html += "<div><a id=\"confirm-btn-cancel\"  href=\"javascript:void(0);\" >取消</a></div></div></div>"; 
    _html +="<div  class=\"confirm-bg\" style=\"display: block;\"></div>";
	$('body').append(_html);
}

var loginWin = function(){
	var _html = "<div id=\"popDiv\" class=\"win-mydiv\" style=\"display: block;\">";
			_html += "<div class=\"win-titleDiv\">&nbsp;&nbsp;登录";
			_html += "<a class=\"win-close\"	href=\"javascript:void(0);\" onclick=\"javascript:hideDiv();\">";
			_html += "<img src=\"images/close.png\">";
			_html += "</a></div>";
			_html += "<div class=\"win-loginDiv\">";
			_html += "<form  id=\"form-login\">";
			_html += "<table id=\"tb\">";
			_html += "<tr><td>";
			_html += "<span	style=\"height: 30px; float: left; margin-top: 8px; font-size: 14px;\">账号</span><br>";
			_html += "<input type=\"text\" name=\"username\" id=\"username\" value=\"admin\"><br>";
			_html += "<span id=\"span1\" style=\"color: red; font-size: 12px;\"></span>";
			_html += "</tr></td><tr><td>";
			_html += "<span	style=\"height: 30px; float: left; margin-top: 8px; font-size: 14px;\">密码</span><br>";
			_html += "<input type=\"password\" name=\"password\" id=\"password\" value=\"123456\"><br>";
			_html += "<span id=\"span2\" style=\"color: red; font-size: 12px;\"></span></td>";
			_html += "</tr></td><tr><td>";
			_html += "<div style=\"height: 16px; margin-top: 12px;\">";
			_html += "<span	style=\"height: 30px; margin-top: 8px; font-size: 13px; margin-left: 260px;\">";
			_html += "<a href=\"/user/forgetPassword\">忘记密码</a></span><br>";
			_html += "</div>";
			_html += "</tr></td><tr><td>";
			_html += "<input id=\"login-button\" type=\"button\" value=\"登  录\"	onclick=\"checkUser(2);\">";
			_html += "</tr></td></table></form>";
			_html += "<div id=\"no-account\">还没账号，<a href=\"public/user/register\">立即免费注册</a>";
			_html += "</div>";
			_html += "<div style=\"border-bottom: 1px solid #DADADA; margin-top: 30px;\">";
			_html += "<a id=\"changeQrcode\" href=\"javascript:void(0);\" onclick=\"javascript:changeQrcode();\"";
			_html += "style=\"float: right; font-size: 14px; color: blue; margin-top: -19px;\">扫码登录</a></div>";
			_html += "<div style=\"text-align: left; font-size: 12px; margin-top: 10px; float: left; color: #666666; width: 100%; margin-left: 5px;\">使用第三方账号登录</div>";
			_html += "<div style=\"float: left; margin-top: 3px; margin-left: 5px;\">";
			_html += "<img alt=\"\" src=\"images/weixing.png\" width=\"25\" height=\"25\">&nbsp;&nbsp;";
			_html += "<img alt=\"\" src=\"images/qq.png\" width=\"25\" height=\"25\">";
			_html += "</div></div></div>";
			_html += "<div id=\"bg\" class=\"win-bg\" style=\"display: block;\"></div>";
			$('body').append(_html);
	};

/**
 * 对象转JSON
 */
var dataToJson = function(data){
	if(!data){
		return null;
	}
 return JSON.parse(JSON.stringify(data));
};

/**
 * 至少选择一条数据
 */
var selectedLeastOne = function(selectedRows){
	if(!selectedRows || selectedRows.length <=0){
		alertMessageWin("请至少选择一条数据");
		return false;
	}
	return true;
};

/**
 * table列表编辑选择
 */
var phxCurrentRow = function($table){
	var $index = parseInt($table.find("tr[class='selected']").attr('data-index'));
	return $table.bootstrapTable('getData')[$index];
};

/**
 * 获取选择的列表数据ID集合
 */
var phxSelectedRowIds =  function($table){
	 return $.map($table.bootstrapTable('getSelections'), function (row) {
         return row.id
     });
};

//关闭消息弹出框
$(function(){
	//弹出框
	$('body').on('click','.alert-close',function(){
		$('body .alert-win').css("display","none");
		$('body .alert-bg').css("display","none");
	});
	//确认框
	$('body').on('click','.confirm-close',function(){
		$('body .confirm-win').css("display","none");
		$('body .confirm-bg').css("display","none");
	});
	//登录框
	$('body').on('click','.win-close',function(){
		$('body .win-mydiv').css("display","none");
		$('body .win-bg').css("display","none");
	});
});

(function($){
    	jQuery.util = {
    			confirm:function(message, callback){  
    				//这里写插件代码  
    				confirmMessageWin(message);
    				$.util.show(function(result){
    					if( callback ) callback(result);
    				});
    			},
    			alert:function(message){
    				alertMessageWin(message);
    			},
    			login:function(){//登录
    				loginWin();
    			},
    			show:function(callback){
    				$("body #confirm-btn-ok").click( function() {  
                        if(callback) callback(true);
                        $('body .confirm-win').css("display","none")
                		$('body .confirm-bg').css("display","none")
                    });  
                    $("body #confirm-btn-cancel").click( function() {  
                        if(callback) callback(false);
                        $('body .confirm-win').css("display","none")
                		$('body .confirm-bg').css("display","none")
                    });  
                    $("body #confirm-btn-ok").focus();  
                    $("body #confirm-btn-ok,body #confirm-btn-cancel").keypress( function(e) {  
                        if( e.keyCode == 13 ) $("body #confirm-btn-ok").trigger('click');  
                        if( e.keyCode == 27 ) $("body #confirm-btn-cancel").trigger('click');  
                    });  
    			},
    			ajaxResult:function(url,params,callBack){
    				ajaxResult(url,params,callBack);
    			},
    			ajaxAsyncResult:function(url,params,callBack){
    				ajaxAsyncResult(url,params,callBack);
    			},
    			date2str:function(value, formatStyle){
    				if(!value){
    					return '-';
    				}
    				var date = new Date(value);
    				return date2str(date, formatStyle);
    			},
    			dataToJson:function(data){
    				return dataToJson(data);
    			},
    			getBasePath:function(){
    				return window.location.origin+"/park-web";
    			},
    			selectedOneRow:function(selectedRows){
    				return selectedLeastOne(selectedRows);
    			},
    			phxCurrentRow:function($table){
    				return phxCurrentRow($table);
    			},
    			phxSelectedRowIds:function($table){
    				return phxSelectedRowIds($table);
    			}
    	}
})(jQuery);  


